
import time

from selenium.common.exceptions import TimeoutException
from selenium.webdriver import ActionChains
from selenium.webdriver.common.by import By
from selenium.webdriver.remote.webdriver import WebDriver
from selenium.webdriver.remote.webelement import WebElement
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions

from Lib.zcm.assistant import FwVariables


class ElementFunction(object):
    """页面级别的操作，偏底层，为了绕开一些而面时的报错
    """

    def __init__(self, driver: WebDriver):
        self._driver = driver

    def click(self, element: WebElement):
        """单击，可以避免元素的点击时，报不能操作的错误
        """
        ActionChains(self._driver).move_to_element(element).click(element).perform()

    def try_find_element_in_page(self, selector, selector_type=By.XPATH, timeout: int = None):
        """在整个页面上找到元素，如果没找到则返回None
        """
        timeout = timeout or FwVariables.get_wait_time_out()
        find_element = None
        try:
            find_element = WebDriverWait(self._driver, timeout).until(
                expected_conditions.presence_of_element_located((selector_type, selector)))
        except TimeoutException:
            pass
        return find_element

    def send_keys(self, keys):
        """发送按键"""
        ActionChains(self._driver).send_keys(keys).perform()

    @staticmethod
    def wait_element_displayed(element: WebElement, timeout: int = None, poll_frequency: int = 0.5):
        # 等待元素显示
        timeout = timeout or FwVariables.get_wait_time_out()
        end_time = time.time() + timeout
        while True:
            value = element.is_displayed()
            if value:
                return value
            time.sleep(poll_frequency)
            if time.time() > end_time:
                break
        return element.is_displayed()

